#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
bcosliteclientpy is a python client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/)
bcosliteclientpy is free software: you can redistribute it and/or modify it under the
terms of the MIT License as published by the Free Software Foundation. This project is
distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Thanks for
authors and contributors of eth-abi, eth-account, eth-hash，eth-keys, eth-typing, eth-utils,
rlp, eth-rlp , hexbytes ... and relative projects
@author: kentzhang
@date: 2019-06
"""

import logging
from logging import handlers
import os
import sys
import threading

from client_config import client_config


def setup_logger():
    # 主线程未捕获的异常 hook
    def sys_hook(exc_type, exc_value, exc_traceback):
        # 报错在日志文件里存一遍
        logging.error("未捕获的异常", exc_info=(exc_type, exc_value, exc_traceback))
    sys.excepthook = sys_hook
    # 子线程未捕获的异常 hook
    # https://github.com/python/cpython/issues/42148#issuecomment-1094010713
    def thread_hook(args):
        if args.exc_type is SystemExit:
            return
        sys.excepthook(args.exc_type, args.exc_value, args.exc_traceback)
    threading.excepthook = thread_hook
setup_logger()

logger = logging.getLogger(__name__)
logfile = client_config.logdir + "/client.log"
if os.path.exists(client_config.logdir) is False:
    os.mkdir(client_config.logdir)
handler = handlers.TimedRotatingFileHandler(logfile, when="D", interval=1, backupCount=3)  # 切割日志
handler.suffix = "%Y%m%d"  # 切割后的日志设置后缀
formatter = logging.Formatter(
    fmt="%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] pid:%(process)d tid:%(thread)d %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

statlogger = logging.getLogger("STAT")
logfile = client_config.logdir + "/stat.log"
handler = handlers.TimedRotatingFileHandler(logfile, when="D", interval=1, backupCount=3)  # 切割日志
handler.suffix = "%Y%m%d"  # 切割后的日志设置后缀
handler.setFormatter(formatter)
statlogger.addHandler(handler)
statlogger.setLevel(logging.DEBUG)
